<?php
/**
 * File: SyncController.clas.php
 * Author: camy <375766145@qq.com>
 * Time: 2018/3/20 17:12
 */

namespace Command\Controller;

use Common\Service\User;

/**
 * 导入钉钉数据
 * @package Command\Controller
 */
class SyncController extends ConsoleController
{
    public function index()
    {
        echo '同步钉钉数据：' . PHP_EOL;
        try {
            M()->startTrans();
            echo '正在同步部门数据...' . PHP_EOL;
            $this->syncDepartment();
            echo '正在同步用户数据...' . PHP_EOL;
            $this->syncUser();
            M()->commit();
            echo '钉钉数据同步成功！' . PHP_EOL;
            return self::ExitOK;
        } catch (\Exception $e) {
            M()->rollback();
            echo "钉钉数据同步失败：" . $e->getMessage() . PHP_EOL;
            return self::ExitFAIL;
        }
    }

    /**
     * 同步部门
     * @throws \Exception
     */
    private function syncDepartment()
    {
        //获取部门
        $list = dingtalk()->getDepartmentList();
        if (empty($list['department'])) {
            throw new \Exception('钉钉部门数据为空!');
        }
        foreach ($list['department'] as $item) {
            $department = M('department')->find($item['id']);
            if (!$department) {
                $data['id'] = $item['id'];
                $data['parent_id'] = intval($item['parentid']);
                $data['name'] = $item['name'];
                $insertData[] = $data;
            }
        }
        //保存部门添加
        $res = M('department')->addAll($insertData);
        if (!$res) {
            throw new \Exception('同步部门数据失败!');
        }
    }

    /**
     * 同步用户
     */
    private function syncUser()
    {
        $departmentList = M('department')->select();
        if ($departmentList) {
            //按部门id同步用户
            foreach ($departmentList as $item) {
                $this->syncUserByDepartment($item['id']);
            }
        } else {
            throw new \Exception('数据库部门为空!');
        }
    }

    /**
     * 按部门同步用户
     * @param $departmentId
     */
    private function syncUserByDepartment($departmentId)
    {
        $result = dingtalk()->getDepartmentUsers($departmentId);
        if ($result['userlist']) {
            foreach ($result['userlist'] as $value) {
                $userid = $value['userid'];
                //判断用户是否存在
                $user = M('user')->where(['userid' => $userid])->find();
                if (!$user) {
                    $this->saveUser($userid);
                }
            }
        }
    }

    /**
     * 保存用户
     */
    private function saveUser($userid)
    {
        $userInfo = dingtalk()->getUserInfo($userid);
        //用户数据
        $userData = array(
            'name' => $userInfo['name'],
            'userid' => $userInfo['userid'],
            'dingid' => $userInfo['dingId'],
            'unionid' => $userInfo['unionid'],
            'active' => $userInfo['active'],
            'is_admin' => $userInfo['isAdmin'],
            'is_boss' => $userInfo['isBoss'],
            'avatar' => strval($userInfo['avatar']),
            'mobile' => strval($userInfo['mobile']),
            'email' => strval($userInfo['email']),
            'position' => strval($userInfo['position']),
        );
        //获取不重复authKey
        $userService = User::instance();
        $userData['auth_key'] = $userService->uniqueAuthKey();
        $res = M('user')->add($userData);
        if (!$res) {
            throw new \Exception('用户：' . $userData['name'] . ' 信息保存失败！');
        }
        //同步用户-部门关系
        $departmentIds = $userInfo['department'];
        if ($departmentIds) {
            foreach ($departmentIds as $departmentId) {
                $data['department_id'] = $departmentId;
                $data['user_userid'] = $userData['userid'];
                $userDepartmentData[] = $data;
            }
            $res = M('userDepartment')->addAll($userDepartmentData);
            if (!$res) {
                throw new \Exception('用户：' . $userData['name'] . ' 部门关系保存失败！');
            }
        }
        //用户所在部门名称A|B
        $userDepartmentNameArr = M('department')
            ->field('name')
            ->where(['id' => ['in', $departmentIds]])
            ->select();
        $userDepartmentNameArr = array_column($userDepartmentNameArr, 'name');
        $userDepartmentName = implode('|', $userDepartmentNameArr);

        $res = M('user')
            ->where(['userid' => $userData['userid']])
            ->save(['department' => $userDepartmentName]);
        if (!$res) {
            throw new \Exception('用户：' . $userData['name'] . ' 部门名称保存失败！');
        }
    }
}